package thu.infinity.facebook;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import thu.infinity.commons.AggregatorHandler;
import thu.infinity.commons.Task;
import thu.infinity.facebook.QueryFriendsTask.MyAlbum;
import thu.infinity.thrift.Constants;
import thu.infinity.thrift.PhotoEntry;

public class QueryAlbumsTask extends Task {
	FacebookUser fbUser;
	Vector<MyAlbum> albumList;
	
	public QueryAlbumsTask(long expireTime, long period) {
		super(expireTime, period);
		// TODO Auto-generated constructor stub
	}
	
	public QueryAlbumsTask(FacebookUser fbUser, Vector<MyAlbum> albumList, AggregatorHandler handler) {
		this.fbUser = fbUser;
		this.albumList = albumList;
		this.handler = handler;
		this.isPeriodical = false;
	}
	
	@Override
	public void execute() {
		// TODO Auto-generated method stub
		Vector<String> allUrl = new Vector<String>();
		for (int i = 0; i < albumList.size(); i++) {
			MyAlbum mAlbum = albumList.get(i);
			if (mAlbum.type==Constants.PhotoEntryTypePhoto)
				allUrl.add(albumList.get(i).id + "/photos");
			else
				allUrl.add(albumList.get(i).id + "/videos");
		}
		System.out.println("albumList size: " + albumList.size());
		Vector<PhotoEntry> peList = new Vector<PhotoEntry>();
		try {
			JSONArray allPhotos = fbUser.fbconn.batchAllGet(allUrl);
			for (int i = 0; i < allPhotos.length(); i++) {
				System.out.println("Album " + i + "/" + allPhotos.length() + " get.");
				String photoRes = allPhotos.getJSONObject(i).getString("body");
				JSONObject photoJson = FacebookUtil.parseJson(photoRes);
				JSONArray photoArray = photoJson.getJSONArray("data");
				MyAlbum mAlbum = albumList.get(i);
				for (int j = 0; j < photoArray.length(); j++) {
					JSONObject photo = photoArray.getJSONObject(j);
					String photoId = photo.getString("id");
					String photoSrc = photo.getString("source");
					String pic = photo.getString("picture");
					
					System.out.println("Photos " + j + " " + photoId);
					
					PhotoEntry photoEnt = new PhotoEntry();
					photoEnt.updatedTime = photo.getString("updated_time");
					
					if (photo.has("name")) {
						photoEnt.name = photo.getString("name");
					} else {
						photoEnt.name = "";
					}
					if (photo.has("comments")) {
						JSONArray comments = photo.getJSONObject("comments").getJSONArray("data");
						for (int k = 0; k < comments.length(); k++) {
							JSONObject tag = comments.getJSONObject(k);
							String createTime = tag.getString("created_time");
							//System.out.println("comments " + tc + " " + ct);
							if (createTime.compareTo(photoEnt.updatedTime) > 0) {
								photoEnt.updatedTime = createTime;
							}
						}
						photoEnt.comments = comments.length();
					} else {
						photoEnt.comments = 0;
					}

					if (photo.has("tags")) {
						JSONArray tags = photo.getJSONObject("tags").getJSONArray("data");
						for (int k = 0; k < tags.length(); k++) {
							JSONObject tag = tags.getJSONObject(k);
							String createTime = tag.getString("created_time");
							if (createTime.compareTo(photoEnt.updatedTime) > 0) {
								photoEnt.updatedTime = createTime;
							}
						}
						photoEnt.tags = tags.length();
					} else {
						photoEnt.tags = 0;
					}
					
					// get the likes
					
					peList.add(photoEnt);
					
					photoEnt.album_id = mAlbum.id;
					if (photo.has("link")) {
						photoEnt.links = photo.getString("link");
					} else {
						photoEnt.links = "";
					}
					photoEnt.id = photoId;
					photoEnt.source = photoSrc;
					photoEnt.picture = pic;
					photoEnt.type = (short) mAlbum.type;

					//System.out.println("P " + pe.id + " " + pe.name + " comments: " + pe.comments + " tags: " + pe.tags + " likes: " + pe.likes + "\n" + pe.links);

					//if (photoEnt.updatedTime.compareTo(fbUser.updatedTime[i]) > 0) {
						/*  old version of cache photo
						String sourceFn = (mAlbum.type==Constants.PhotoEntryTypePhoto) ? Util.photoName(photoEnt.id) : Util.videoName(photoEnt.id);
						FacebookUtil.cachePhoto(photoSrc, sourceFn);
						photoEnt.photoSize = Util.newFile(sourceFn).length();
						String thumbFn = Util.photoThumbName(photoEnt.id);
						FacebookUtil.cachePhoto(pic, thumbFn);
						photoEnt.thumbSize = Util.newFile(thumbFn).length();
						*/
					
						// new version using CachePhotoTask
						
						CachePhotoTask cachePhoto = new CachePhotoTask(photoEnt, mAlbum.type, handler);
						handler.getScheduler().AddTask(cachePhoto);
						//synchronized (fnList) {
							//fnList.add(dirEntryFromFileName(sourceFn, pe.updatedTime, Constants.PriorityNormal));
							//fnList.add(dirEntryFromFileName(thumbFn, pe.updatedTime, Constants.PriorityThumb));
						//}
						
						/*
						synchronized (largetTime) {
							if (pe.updatedTime.compareTo(largetTime.time) > 0) {
								//System.out.println("***Largest time updated from " + largetTime + " to " + pe.updatedTime);
								largetTime.time = pe.updatedTime;												
							}
						}
						*/
						synchronized (peList) {
							peList.add(photoEnt);
						}
					//}
				}
			}
			System.out.println("end");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FacebookError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public boolean checkCondition() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected Task genNextTask() {
		// TODO Auto-generated method stub
		return null;
	}

}
